import { NextRequest, NextResponse } from 'next/server';
import {
  ChatSessionOperations,
  ChatMessageOperations,
} from '@/lib/database-operations';
import { getOptimizedDeepSeekClient } from '@/lib/deepseek';
import { ConversationContextManager } from '@/lib/conversation-context';
import { enhancedRAG } from '@/lib/enhanced-rag';
import { intentRecognitionService } from '@/lib/intent-recognition';
import { HumanMessage, SystemMessage } from '@langchain/core/messages';
import { PromptTemplate } from '@langchain/core/prompts';
import { RunnableSequence } from '@langchain/core/runnables';
import { StringOutputParser } from '@langchain/core/output_parsers';
import { v4 as uuidv4 } from 'uuid';
import { embeddingModel, qdrantClient } from '@/lib/vectorization';

// 初始化对话上下文管理器
const contextManager = new ConversationContextManager();

// RAG系统提示模板
const RAG_SYSTEM_PROMPT = `你是一个智能助手，请基于以下上下文信息回答用户问题：

上下文信息：
{context}

用户问题：{question}

请根据上下文信息提供准确、有帮助的回答。如果上下文信息不足以回答问题，请说明并提供你的最佳建议。`;

// DeepSeek聊天实例
const deepseekChat = getOptimizedDeepSeekClient('rag');

// 向量搜索函数
async function vectorSearch(
  query: string,
  limit: number = 5,
  threshold: number = 0.7
) {
  try {
    // 生成查询向量
    const queryEmbedding = await embeddingModel.embedQuery(query);

    // 在Qdrant中搜索相似向量
    const searchResult = await qdrantClient.search('documents', {
      vector: queryEmbedding,
      limit,
      score_threshold: threshold,
      with_payload: true,
    });

    return searchResult.map(result => ({
      id: result.id,
      score: result.score || 0,
      content: result.payload?.content || '',
      title: result.payload?.title || '',
      document_id: result.payload?.document_id || '',
      chunk_index: result.payload?.chunk_index || 0,
    }));
  } catch (error) {
    console.error('向量搜索失败:', error);
    return [];
  }
}

// 生成RAG响应
async function generateRAGResponse(question: string, context: string) {
  try {
    const prompt = PromptTemplate.fromTemplate(RAG_SYSTEM_PROMPT);

    const chain = RunnableSequence.from([
      prompt,
      deepseekChat,
      new StringOutputParser(),
    ]);

    const response = await chain.invoke({
      context,
      question,
    });

    return response;
  } catch (error) {
    console.error('生成RAG响应失败:', error);
    throw error;
  }
}

// 聊天API
export async function POST(request: NextRequest) {
  try {
    const { message, sessionId, userId, useRAG = true } = await request.json();

    if (!message?.trim()) {
      return NextResponse.json(
        { success: false, error: '消息不能为空' },
        { status: 400 }
      );
    }

    let currentSessionId = sessionId;

    // 如果没有会话ID，创建新会话
    if (!currentSessionId) {
      currentSessionId = await ChatSessionOperations.create(
        message.slice(0, 50) + (message.length > 50 ? '...' : ''),
        userId
      );
    }

    // 保存用户消息
    const userMessageId = await ChatMessageOperations.create({
      session_id: currentSessionId,
      role: 'user',
      content: message,
      created_at: new Date().toISOString(),
      metadata: {
        timestamp: Date.now(),
        use_rag: useRAG,
      },
    });

    let response: string;
    let ragResults: any[] = [];
    let conversationContext: any;

    // 获取会话历史消息
    const existingMessages =
      await ChatMessageOperations.getBySessionId(currentSessionId);

    if (useRAG) {
      // 使用增强的RAG系统进行智能检索
      const retrievalResult = await enhancedRAG.intelligentRetrieval(
        message,
        existingMessages,
        userId
      );

      ragResults = retrievalResult.results.map(result => ({
        title: result.title || '未知',
        content: result.content || '',
        similarity: result.score,
      }));

      // 构建对话上下文（包含意图识别）
      conversationContext = await contextManager.buildContext(
        existingMessages,
        message,
        ragResults.map(r => r.content).join('\n'),
        userId
      );

      // 根据意图和RAG状态选择最优的DeepSeek配置
      let modelPreset: 'conversational' | 'rag' | 'creative' | 'analytical' | 'concise' = 'conversational';
      if (useRAG) {
        modelPreset = 'rag';
      } else if (conversationContext.contextInfo.intentResult) {
        // 根据意图类型选择模型配置
        switch (conversationContext.contextInfo.intentResult.intent) {
          case 'creative':
            modelPreset = 'creative';
            break;
          case 'analysis':
            modelPreset = 'analytical';
            break;
          case 'instruction':
          case 'help':
            modelPreset = 'concise';
            break;
          default:
            modelPreset = 'conversational';
        }
      }

      const deepseekClient = getOptimizedDeepSeekClient(modelPreset);

      // 生成AI回复
      const messages = [
        ...conversationContext.messages,
      ];

      const result = await deepseekClient.invoke(messages);
      response = result.content as string;
    } else {
      // 普通对话模式 - 也需要构建对话上下文
      conversationContext = await contextManager.buildContext(
        existingMessages,
        message,
        undefined,
        userId
      );

      const deepseekClient = getOptimizedDeepSeekClient('conversational');
      const messages = [
        ...conversationContext.messages,
      ];

      const result = await deepseekClient.invoke(messages);
      response = result.content as string;
    }

    // 保存AI响应
    const aiMessageId = await ChatMessageOperations.create({
      session_id: currentSessionId,
      role: 'assistant',
      content: response,
      created_at: new Date().toISOString(),
      metadata: {
        timestamp: Date.now(),
        rag_results: ragResults,
        context_used: useRAG && ragResults.length > 0,
      },
    });

    // 更新用户画像（如果有意图识别结果）
    if (
      useRAG &&
      conversationContext &&
      conversationContext.contextInfo.intentResult &&
      userId
    ) {
      intentRecognitionService.updateUserProfile(
        userId,
        conversationContext.contextInfo.intentResult.intent,
        conversationContext.contextInfo.responseStrategy
      );
    }

    return NextResponse.json({
      success: true,
      data: {
        session_id: currentSessionId,
        user_message_id: userMessageId,
        ai_message_id: aiMessageId,
        response,
        rag_results: useRAG ? ragResults : undefined,
        context_used: useRAG && ragResults.length > 0,
        intentAnalysis:
          useRAG && conversationContext && conversationContext.contextInfo.intentResult
            ? {
                intent: conversationContext.contextInfo.intentResult.intent,
                confidence: conversationContext.contextInfo.intentResult.confidence,
                keywords: conversationContext.contextInfo.intentResult.keywords,
                emotionalTone: conversationContext.contextInfo.intentResult.emotionalTone,
                responseStrategy: conversationContext.contextInfo.responseStrategy,
              }
            : null,
      },
    });
  } catch (error) {
    console.error('聊天处理失败:', error);
    return NextResponse.json(
      { success: false, error: '聊天处理失败' },
      { status: 500 }
    );
  }
}

// 获取聊天历史
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const sessionId = searchParams.get('sessionId');
    const userId = searchParams.get('userId');
    const limit = parseInt(searchParams.get('limit') || '50');
    const offset = parseInt(searchParams.get('offset') || '0');

    if (sessionId) {
      // 获取特定会话的消息
      const messages = await ChatMessageOperations.getBySessionId(
        sessionId,
        limit,
        offset
      );
      return NextResponse.json({
        success: true,
        data: messages,
      });
    } else if (userId) {
      // 获取用户的所有会话
      const sessions = await ChatSessionOperations.getByUserId(
        userId,
        limit,
        offset
      );
      return NextResponse.json({
        success: true,
        data: sessions,
      });
    } else {
      return NextResponse.json(
        { success: false, error: '需要提供sessionId或userId' },
        { status: 400 }
      );
    }
  } catch (error) {
    console.error('获取聊天历史失败:', error);
    return NextResponse.json(
      { success: false, error: '获取聊天历史失败' },
      { status: 500 }
    );
  }
}
